package top.huxy.boot.controller.publicly;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import top.huxy.boot.annotation.NoRecordRequest;
import top.huxy.boot.annotation.RequestRemake;
import top.huxy.boot.api.WeatherApi;
import top.huxy.boot.config.Constant;
import top.huxy.boot.model.dto.Pager;
import top.huxy.boot.model.vo.VONavSite;
import top.huxy.boot.model.vo.VOWeather;
import top.huxy.boot.model.vo.VOWeatherForecase;
import top.huxy.boot.service.NavSiteService;
import top.huxy.boot.service.BackgroundImageService;
import top.huxy.boot.util.CollectionUtils;
import top.huxy.boot.util.IPAddressUtils;
import top.huxy.boot.util.obj.Result;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("/home")
@RestController
public class HomeController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private NavSiteService navSiteService;

    @Autowired
    private BackgroundImageService backgroundImageService;

    @Autowired
    WeatherApi weatherApi;

    @GetMapping("/search")
    @RequestRemake("引擎搜索")
    public Result search(@RequestParam(value = "engine", defaultValue = "baidu") String engine, @RequestParam("search") String search) {
        if ("".equals(search)) {
            return null;
        }
        //bing的搜索有限制，所以bing暂不实现
        if ("bing".equals(engine)) {
            engine = "baidu";
        }

        Exception ex = null;
        String engineUrl = getEngineUrl(engine, search);
        if (engineUrl == null) {
            return Result.clientError("没有匹配的搜索引擎:" + engine);
        }

        QueryResult queryResult = null;
        try {
            queryResult = requestEngine(engineUrl, engine);
        } catch (Exception e) {
            ex = e;
            e.printStackTrace();
        }

        if (queryResult != null) {
            queryResult.key = search;
            return Result.success(queryResult);
        }

        if (ex != null) {
            return Result.serverError("服务器繁忙", ex.getMessage());
        }

        return Result.clientError("不是预期的结果");
    }

    private QueryResult requestEngine(String engineUrl, String engine) {
        String res = restTemplate.getForObject(engineUrl, String.class);
        if ("baidu".equals(engine)) {
            return parseBaiduResult(res);
        } else if ("sougou".equals(engine)) {
            return parseSougouResult(res);
        } else if ("360".equals(engine)) {
            return parse360Result(res);
        }
        return null;
    }

    private QueryResult parse360Result(String res) {
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONArray result = jsonObject.getJSONArray("result");

        LinkedList<String> list = new LinkedList<>();
        for (Object o : result) {
            if (o instanceof JSONObject) {
                JSONObject item = ((JSONObject) o);
                list.add(item.getString("word"));
            }
        }
        return new QueryResult(list);
    }

    private String getEngineUrl(String engine, String search) {
        if ("baidu".equals(engine)) {
            return Constant.BAIDU_SEARCH_ENGINE.replace("${search}", search);
        } else if ("sougou".equals(engine)) {
            return Constant.SOUGOU_SEARCH_ENGINE.replace("${search}", search);
        } else if ("360".equals(engine)) {
            return Constant.$360_SEARCH_ENGINE.replace("${search}", search);
        }
        return null;
    }

    Pattern sogouPattern = Pattern.compile("window.sogou.sug\\((.*),-1\\);");

    private QueryResult parseSougouResult(String res) {
        Matcher matcher = sogouPattern.matcher(res);
        if (matcher.find()) {
            String group = matcher.group(1);
            JSONArray objects = JSON.parseArray(group);
            JSONArray jsonArray = objects.getJSONArray(1);
            List<String> list = jsonArray.toJavaList(String.class);
            return new QueryResult(list);
        }
        return null;
    }

    private QueryResult parseBaiduResult(String res) {
        JSONObject object = JSON.parseObject(res);
        JSONArray g = object.getJSONArray("g");
        LinkedList<String> result = new LinkedList<>();
        for (Object o : g) {
            if (o instanceof JSONObject) {
                JSONObject item = ((JSONObject) o);
                result.push(item.getString("q"));
            }
        }
        return new QueryResult(result);
    }

    @Getter
    private static class QueryResult {
        private String key;
        private List<String> list;

        public QueryResult(List<String> list) {
            this.list = list;
        }
    }

    @GetMapping("/getNavSite")
    @RequestRemake("获取导航")
    public Result getNavSite() {
        List<VONavSite> navSiteList = navSiteService.getNavSiteList();
        return Result.success(navSiteList);
    }

    @RequestRemake("保存网址")
    @GetMapping("/saveHistorySite")
    public Result saveHistorySite(@RequestParam("id") Integer id, @CookieValue(Constant.USER_TOKEN_NAME) String userToken) {
        this.navSiteService.saveHistorySite(id, userToken);
        return Result.success("保存成功");
    }

    @RequestRemake("获取用户保存的网址")
    @GetMapping("/getHistorySite")
    public Result getHistorySite(Pager pager, @CookieValue(value = Constant.USER_TOKEN_NAME) String userToken) {
        List<VONavSite.NavItem> list = this.navSiteService.getHistorySite(pager, userToken);
        PageInfo<VONavSite.NavItem> pageInfo = new PageInfo<>(list);
        return Result.success(pageInfo);
    }

    @RequestRemake("清除用户的网站历史记录")
    @PostMapping("/removeAllHistory")
    public Result removeAllHistory(@CookieValue(Constant.USER_TOKEN_NAME) String userToken) {
        this.navSiteService.removeAllHistory(userToken);
        return Result.success("清除成功");
    }

    @RequestRemake("删除用户的网站历史记录")
    @PostMapping("/removeSiteById")
    public Result removeSiteById(@CookieValue(Constant.USER_TOKEN_NAME) String userToken, @RequestParam("ids") String ids) {
        this.navSiteService.removeSiteById(userToken, ids);
        return Result.success("删除成功");
    }

    @NoRecordRequest
    @GetMapping("/getBg")
    public Result getBg() {
        return Result.success(backgroundImageService.getCurrentBg());
    }

    @RequestRemake("获取天气信息")
    @GetMapping("/getWeather")
    public Result getWeather() {
        HashMap<String, Object> res = CollectionUtils.createHashMap(2, String.class, Object.class);
        String ip = IPAddressUtils.getRequestIp();
        List<VOWeatherForecase> forecast = weatherApi.getWeatherForecast(ip);
        VOWeather now = weatherApi.getNowWeather(ip);
        res.put("forecast",forecast);
        res.put("now",now);
        return Result.success(res);
    }
}
